#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <json/json.h>
#include <string>


#define BUFFER_SIZE 1024

using namespace std;

int main(int argc, const char *argv[])
{
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8088);
    server_addr.sin_addr.s_addr = inet_addr("47.96.253.33");
    bzero(&(server_addr.sin_zero), 8);

    int server_sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_sock_fd == -1)
    {
        perror("socket error");
        return 1;
    }
    char recv_msg[BUFFER_SIZE];
    char input_msg[BUFFER_SIZE];

    if (connect(server_sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) == 0)
    {
        fd_set client_fd_set;
        struct timeval tv;

        while (1)
        {
            tv.tv_sec = 20;
            tv.tv_usec = 0;
            FD_ZERO(&client_fd_set);
            FD_SET(STDIN_FILENO, &client_fd_set);   // 标准输入  加入文件描述符集，让select监听输入事件 。
            FD_SET(server_sock_fd, &client_fd_set); // 服务端

            select(server_sock_fd + 1, &client_fd_set, NULL, NULL, &tv);
            if (FD_ISSET(STDIN_FILENO, &client_fd_set)) // 输入数据则发送
            {
                bzero(input_msg, BUFFER_SIZE);
                fgets(input_msg, BUFFER_SIZE, stdin);
                Json::Value data;
                Json::StyledWriter sWriter;
                data["type"] = "web";
                data["x"] = 0.1;
                data["y"] = 0.2;
                data["z"] = 0.3;
                string data_str = sWriter.write(data);
                if (send(server_sock_fd, data_str.c_str(), BUFFER_SIZE, 0) == -1)
                {
                    perror("发送消息出错!\n");
                }
            }
            if (FD_ISSET(server_sock_fd, &client_fd_set))
            {
                bzero(recv_msg, BUFFER_SIZE);
                long byte_num = recv(server_sock_fd, recv_msg, BUFFER_SIZE, 0);
                if (byte_num > 0)
                {
                    if (byte_num > BUFFER_SIZE)
                    {
                        byte_num = BUFFER_SIZE;
                    }
                    recv_msg[byte_num] = '\0';
                    printf("服务器:%s\n", recv_msg);
                }
                else if (byte_num < 0)
                {
                    printf("接受消息出错!\n");
                }
                else
                {
                    printf("服务器端退出!\n");
                    exit(0);
                }
            }
        }
        //}
    }
    return 0;
}

